#include "astar_file.h"
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

unsigned short ASTAR_FILE::get_le_short( void )
{
	unsigned short s;
	read( &s, 2 );
	return s;
}

unsigned short ASTAR_FILE::get_be_short( void )
{
	unsigned short s;
	unsigned char buf[ 2 ];
	read( buf, 2 );
	s = (( unsigned short ) buf[ 0 ]) << 8 | buf[1];
	return s;
}

int ASTAR_FILE::getchr( void )
{
	unsigned char a;
	read( &a, 1 );
	return a;
}

float ASTAR_FILE::getfloat()
{
	assert( 0 );
	return 0.0f;
}

void ASTAR_FILE::gets( char *dst, int maxsize )
{
	int i;
	for ( i = 0; i < maxsize; ++i )
	{
		dst[ i ] = getchr();
		if ( dst[ i ] == 0 )
		{
			break;
		}
	}
}

bool ASTAR_FILE::eof( void )
{
	if ( tell() >= size() )
	{
		return true;
	}
	return false;
}

ASTAR_FILE_DISK::ASTAR_FILE_DISK( const char *filename )
{
	m_fptr = fopen( filename, "rb" );
	if ( m_fptr == NULL )
	{
		fprintf(stderr, "Unable to open file %s\n", filename);
		exit( 1 );
	}

	fseek( m_fptr, 0, SEEK_END );
	m_size = ftell( m_fptr );
	fseek( m_fptr, 0, SEEK_SET );
}

ASTAR_FILE_DISK::~ASTAR_FILE_DISK()
{
	fclose( m_fptr );
	m_fptr = NULL;
}

unsigned int ASTAR_FILE_DISK::size( void )
{
	return m_size;
}

void ASTAR_FILE_DISK::read( void *dst, unsigned int bytes )
{
	assert( fread( dst, 1, bytes, m_fptr ) == bytes );
}

void ASTAR_FILE_DISK::write( const void *src, unsigned int bytes )
{
	assert( fwrite( src, 1, bytes, m_fptr ) == bytes );
}

void ASTAR_FILE_DISK::seek( unsigned int pos )
{
	fseek( m_fptr, pos, SEEK_SET );
}

unsigned int ASTAR_FILE_DISK::tell( void )
{
	return ftell( m_fptr );
}	

ASTAR_FILE_RAM::ASTAR_FILE_RAM( ASTAR_FILE &file )
{
	m_size = file.size();
	m_buffer = new unsigned char[ m_size ];
	assert( m_buffer != NULL );
	m_pos = m_buffer;
	file.read( m_buffer, m_size );
}

ASTAR_FILE_RAM::~ASTAR_FILE_RAM( void )
{
	delete[] m_buffer;
	m_buffer = NULL;
	m_pos = NULL;
	m_size = 0;
}

